#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版Word文档转Markdown转换器
不依赖python-docx库，直接解析docx文件
"""

import os
import re
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Dict, List, Tuple


class SimpleDocxConverter:
    """简化版docx转换器"""
    
    def __init__(self, docx_file: str):
        """
        初始化转换器
        
        Args:
            docx_file: docx文件路径
        """
        self.docx_file = Path(docx_file)
        if not self.docx_file.exists():
            raise FileNotFoundError(f"文件不存在: {docx_file}")
        
        self.output_dir = self.docx_file.parent
        self.images_dir = self.output_dir / "images"
        self.output_file = self.output_dir / f"{self.docx_file.stem}.md"
        
        # 创建输出目录
        self.images_dir.mkdir(exist_ok=True)
        
        self.image_counter = 0
        self.extracted_images = []
        
        # XML命名空间
        self.namespaces = {
            'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
            'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
            'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
            'pic': 'http://schemas.openxmlformats.org/drawingml/2006/picture'
        }
    
    def extract_text_and_images(self) -> Tuple[str, List[str]]:
        """
        从docx文件中提取文本和图片
        
        Returns:
            (文本内容, 提取的图片列表)
        """
        with zipfile.ZipFile(self.docx_file, 'r') as docx_zip:
            # 读取主文档
            try:
                document_xml = docx_zip.read('word/document.xml')
            except KeyError:
                raise ValueError("无效的docx文件格式")
            
            # 解析XML
            root = ET.fromstring(document_xml)
            
            # 提取图片
            self._extract_images_from_zip(docx_zip)
            
            # 提取文本内容
            text_content = self._extract_text_content(root)
            
            return text_content, self.extracted_images
    
    def _extract_images_from_zip(self, docx_zip: zipfile.ZipFile):
        """从zip中提取图片文件"""
        for file_path in docx_zip.namelist():
            if file_path.startswith('word/media/'):
                self.image_counter += 1
                
                # 获取文件扩展名
                ext = Path(file_path).suffix
                img_filename = f"image_{self.image_counter:03d}{ext}"
                img_path = self.images_dir / img_filename
                
                # 提取并保存图片
                with docx_zip.open(file_path) as img_file:
                    with open(img_path, 'wb') as output_file:
                        output_file.write(img_file.read())
                
                self.extracted_images.append(str(img_path))
                print(f"提取图片: {img_filename}")
    
    def _extract_text_content(self, root: ET.Element) -> str:
        """从XML中提取文本内容"""
        content_parts = []
        
        # 遍历所有段落
        for paragraph in root.findall('.//w:p', self.namespaces):
            para_text = self._extract_paragraph_text(paragraph)
            if para_text.strip():
                content_parts.append(para_text)
            
            # 检查段落中是否包含图片
            if self._paragraph_contains_image(paragraph):
                if self.extracted_images:
                    # 为图片添加引用
                    img_index = len([p for p in content_parts if p.startswith('![')])
                    if img_index < len(self.extracted_images):
                        img_path = Path(self.extracted_images[img_index])
                        img_ref = f"![{img_path.name}](images/{img_path.name})"
                        content_parts.append(img_ref)
                        content_parts.append(self._analyze_image_simple(str(img_path)))
        
        return '\n\n'.join(content_parts)
    
    def _extract_paragraph_text(self, paragraph: ET.Element) -> str:
        """提取段落文本"""
        text_parts = []
        
        for text_elem in paragraph.findall('.//w:t', self.namespaces):
            if text_elem.text:
                text_parts.append(text_elem.text)
        
        return ''.join(text_parts)
    
    def _paragraph_contains_image(self, paragraph: ET.Element) -> bool:
        """检查段落是否包含图片"""
        return bool(paragraph.findall('.//pic:pic', self.namespaces))
    
    def _analyze_image_simple(self, image_path: str) -> str:
        """简单的图片内容分析"""
        filename = Path(image_path).name
        
        analysis_text = f"""**图片分析** ({filename}):

这是一个与预选供应商推荐线上化系统相关的图片。可能包含以下内容：
- 业务流程图或系统架构图
- 用户界面设计或操作界面
- 数据表格或统计图表
- 系统功能说明或配置信息

*注：这是基于文件名的初步分析。如需详细分析，请使用AI视觉分析工具。*

---"""
        
        return analysis_text
    
    def convert_to_markdown(self) -> str:
        """转换为Markdown格式"""
        print(f"开始转换: {self.docx_file.name}")
        
        # 提取内容
        text_content, images = self.extract_text_and_images()
        
        # 构建Markdown内容
        markdown_lines = [
            f"# {self.docx_file.stem}",
            "",
            f"*转换自: {self.docx_file.name}*",
            f"*生成时间: {Path(__file__).stat().st_mtime}*",
            "",
            "---",
            "",
        ]
        
        # 分割文本为段落并格式化
        paragraphs = text_content.split('\n\n')
        for para in paragraphs:
            para = para.strip()
            if para:
                # 简单的标题检测
                if len(para) < 100 and not para.startswith('!['):
                    # 可能是标题，添加格式
                    if any(keyword in para for keyword in ['系统', '流程', '功能', '概述', '说明']):
                        markdown_lines.append(f"## {para}")
                    else:
                        markdown_lines.append(para)
                else:
                    markdown_lines.append(para)
                
                markdown_lines.append("")
        
        # 添加图片统计信息
        if images:
            markdown_lines.extend([
                "---",
                "",
                "## 提取的图片文件",
                "",
                f"共提取 {len(images)} 张图片：",
                ""
            ])
            
            for i, img_path in enumerate(images, 1):
                img_name = Path(img_path).name
                markdown_lines.append(f"{i}. {img_name}")
            
            markdown_lines.append("")
        
        return '\n'.join(markdown_lines)
    
    def save_markdown(self, content: str):
        """保存Markdown文件"""
        with open(self.output_file, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"Markdown文件已保存: {self.output_file}")
    
    def convert(self) -> str:
        """执行完整的转换流程"""
        try:
            # 转换为Markdown
            markdown_content = self.convert_to_markdown()
            
            # 保存文件
            self.save_markdown(markdown_content)
            
            # 打印统计信息
            print(f"\n转换完成！")
            print(f"- 输出文件: {self.output_file}")
            print(f"- 提取图片: {len(self.extracted_images)} 张")
            if self.extracted_images:
                print("- 图片列表:")
                for img_path in self.extracted_images:
                    print(f"  • {Path(img_path).name}")
            
            return markdown_content
            
        except Exception as e:
            print(f"转换失败: {e}")
            raise


def main():
    """主函数"""
    print("=" * 60)
    print("简化版 Word文档转Markdown转换器")
    print("=" * 60)
    
    # 查找Word文档
    docx_file = "预选供应商推荐线上化.docx"
    
    if not os.path.exists(docx_file):
        print(f"错误: 找不到文件 '{docx_file}'")
        print("请确保Word文档在当前目录下")
        return 1
    
    try:
        # 创建转换器并执行转换
        converter = SimpleDocxConverter(docx_file)
        converter.convert()
        
        print("\n转换完成！")
        print("=" * 60)
        return 0
        
    except Exception as e:
        print(f"转换失败: {e}")
        import traceback
        traceback.print_exc()
        return 1


if __name__ == "__main__":
    import sys
    sys.exit(main())